/**
 * @class tuan.controller.ProductController
 * @extends extendsClass
 * Description
 */
 Ext.define('tuan.controller.ProductController', {
    extend: 'Ext.app.Controller',
    refs : [
    {ref : 'productGrid', selector : "product_grid_xtype"},
    {ref : 'formProduct', selector : 'sanpham form-product-xtype'},
    {ref : 'comboboxcate', selector : '#comboxCate'}
    ],
    views : ['sanpham.ProductGrid','sanpham.FormProduct'],
    stores : ['CategoriesStore','ProductStore'],
    loaded : false,

    init : function (){

       this.control({
        "product_grid_xtype" : {
            beforerender : this.loadProductGrid
        },
        "#btnAddProduct" : {
            click : this.submitForm
        },
        'form-product-xtype' : {
            beforerender : this.loadCombobox
        },
        '#action_product_grid' : {
            click : this.clickDetail
        }
    })
   },
   clickDetail : function(grid,cell,row,col,e){
    var rec = grid.getStore().getAt(row);
    var action = e.target.getAttribute('class');

    if (action.indexOf("x-action-col-0") != -1) {
                   // console.log('You chose to do THIS to ' + rec.get('id')); //where id is the name of a dataIndex
                   var win = Ext.create("tuan.view.ReviewProduct");
                   record = grid.getStore().getAt(row);
                   var detail = Ext.create("tuan.view.ProductDetail",{
                    data : record.data,
                    height : '500'
                    });
                   console.log(record.data);
                   win.add(detail);
                   win.show();
               }
               else if (action.indexOf("x-action-col-1") != -1) {
                 // console.log('You chose to do THAT to ' + rec.get('id'));
                 Ext.Msg.confirm('Remove product?', 'Are you sure you want to remove this product?',
                    function(choice) {
                        if(choice === 'yes') {
                            var productStore = Ext.getStore('ProductStore');
                            var product = grid.getStore().getAt(row);
                            // var productIndex = productStore.find('id', product.get('id'));
                            productStore.removeAt(product);
                            grid.getStore().removeAt(row);
                        }
                    }
                );   
             }else if(action.indexOf("x-action-col-2") != -1){
                var win = Ext.create("tuan.view.EditProduct");
                record = grid.getStore().getAt(row);
                win.getComponent('edit-product-detail').loadRecord(record);
                win.show();
             }
         },
         loadCombobox : function(){
            storeCates = Ext.getStore('CategoriesStore');
            c = this.getComboboxcate();
    // storeCates.on('load',function(cates){
        c.bindStore(storeCates);
    // });
},
submitForm : function(src){
    var form = src.up('form');
    var p = this.getProductGrid();

    if(form.isValid()){
        data = form.getForm();
        // var productname = data.findField('product_name').getValue();
        // var productprice = data.findField('product_price').getValue();
        // var productweight = data.findField('product_weight').getValue();
        // var cate = data.findField('cate_product').getValue();
        // var file = data.findField('fileimg').getValue();

        // var storeCates = Ext.getStore('CategoriesStore');
        // storeCates.add({product_name : productname,price : productprice,weight : productweight,cate_id : cate});
        // storeCates.sync();
        
        // Ext.Msg.alert('Status', file);

        form.submit({
            url: 'server/form_product.php',
            waitMsg: 'Uploading your photo...',
            success: function(fp, o) {
                data.reset();
                Ext.Msg.alert('Success', 'Processed file "' + o.result.fileName + '" on the server');
                var storeProduct = Ext.getStore("ProductStore"); 
                storeProduct.load();
                storeProduct.on("load",function(record){
                    p.reconfigure(storeProduct);
                });
            },
            failure: function() {
                Ext.Msg.alert("Error", Ext.JSON.decode(this.response.responseText).message);
            }
        });

    }

},
loadProductGrid : function(){

 Ext.Ajax.on("beforerequest", function(){
    Ext.getBody().mask("Loading...", 'loading');
});
 Ext.Ajax.on("requestcomplete", function(){
    window.parent.Ext.getBody().unmask();
});
 Ext.Ajax.on("requestexception", function(){
    Ext.Msg.alert('Error','Sorry something wrong!');
    window.parent.Ext.getBody().unmask();
});
 storeProduct = Ext.getStore("ProductStore"); 

 p = this.getProductGrid();

 storeCates = Ext.getStore('CategoriesStore').load();
 storeCates.on('load',function(cates){
            // 
            localCate = {};
            storeCates.each(function(cate,index) {
                tmp = {};
                tmp['id'] = cate.get('id');
                tmp['catename'] = cate.get('cate_name');

                localCate[index] = tmp;
            });
            localStorage.setItem('localStoreCates', JSON.stringify(localCate));
            storeProduct.load();
            storeProduct.on("load",function(record){
                p.reconfigure(storeProduct);
            });

        });

},
actionIndex : function(){
		// this.loadProductGrid()
		// Ext.getCmp('product_view_zone').remove({xtype : 'product_grid_xtype'});
		if(this.loaded == false){
			
			Ext.getCmp('product_view_zone').add({xtype : 'product_grid_xtype'});
			Ext.getCmp('product_management').add({xtype : 'form-product-xtype'});
			this.loaded = true;
		}
		
	}
});